package com.sh.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;


public class PathUtil {

    public static String getPathNotEndWithSeparator(String path) {
        if (StringUtils.isEmpty(path)) {
            return null;
        }
        if (path.endsWith("/")) {
            path = path.substring(0, path.lastIndexOf("/"));
        }
        return path;
    }

    public static String getPathEndWithSeparator(String path){
        if (StringUtils.isEmpty(path)) {
            return null;
        }
        if (!path.endsWith("/")) {
            path = path + "/";
        }
        return path;
    }

    public static String assembleObjectKey(String path, String objectName) {
        String objectKey = null;

        if (StringUtils.isEmpty(path)) {
            objectKey = objectName;
        } else if (path.endsWith("/")) {
            objectKey = String.format("%s%s", path, objectName);
        } else {
            objectKey = String.format("%s/%s", path, objectName);
        }
        if (objectKey.startsWith("/")) {
            objectKey = objectKey.substring(1,objectKey.length()-1);
        }

        return objectKey;
    }

    public static String assembleObjectKey(String objectPath) {
        if (objectPath.startsWith("/")) {
            objectPath = objectPath.substring(1,objectPath.length()-1);
        }
        return objectPath;
    }

    /**
     * 查找对大公共路径
     * */
    public static String findLongestCommonPath(List<String> paths) {
        if (paths == null || paths.isEmpty()) {
            return "";
        }

        // 将路径列表转换为路径节点列表
        List<String[]> pathSegmentsList = new ArrayList<>();
        for (String path : paths) {
            // 使用 "/" 分割路径
            String[] segments = path.split("/");
            pathSegmentsList.add(segments);
        }

        // 逐步比较每个路径的节点，找到最长公共前缀
        StringBuilder commonPath = new StringBuilder();
        int minPathLength = pathSegmentsList.stream().mapToInt(segments -> segments.length).min().orElse(0);

        // 逐步比较每个路径的节点
        for (int i = 0; i < minPathLength; i++) {
            final int index = i; // 创建一个 effectively final 的变量
            String segment = pathSegmentsList.get(0)[index]; // 取第一个路径的节点
            boolean allMatch = pathSegmentsList.stream()
                    .allMatch(segments -> segments[index].equals(segment));

            if (allMatch) {
                commonPath.append(segment).append("/");
            } else {
                break; // 如果某个节点不匹配，则停止比较
            }
        }

        return commonPath.toString();
    }


}
